﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections;
using System.Diagnostics;
using System.Management;
using System.Threading;

namespace ServerMoniter
{
    public class ServerMoniterCls
    {
        private PerformanceCounter pcCpuLoad = new PerformanceCounter();

        public bool bServiceRunning = true;

        #region API声明
        [DllImport("IpHlpApi.dll")]
        extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);

        [DllImport("User32")]
        private extern static int GetWindow(int hWnd, int wCmd);

        [DllImport("User32")]
        private extern static int GetWindowLongA(int hWnd, int wIndx);

        [DllImport("user32.dll")]
        private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);

        [DllImport("user32", CharSet = CharSet.Auto)]
        private extern static int GetWindowTextLength(IntPtr hWnd);

        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
        #endregion 

        #region 获取CPU信息
        /// <summary>
        /// 获取CPU信息
        /// </summary>
        /// <returns>Hashtable</returns>
        private void GetCPUInfo()
        {
            Hashtable htCpuInfo = new Hashtable();

            //htCpuInfo.Add("CpuNum", iCpuNum);
            //获取总CPU占用率
            //pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            pcCpuLoad.CategoryName = "Processor";
            pcCpuLoad.CounterName = "% Processor Time";
            pcCpuLoad.InstanceName = "_Total";
            float fCpuLoad = pcCpuLoad.NextValue();
            htCpuInfo["monitertype"] = "CPU";
            htCpuInfo["monitertypedetail"] = "";//不填写值，表示总CPU占用率
            htCpuInfo["monitervalue"] = Math.Round(fCpuLoad, 2);
            if (fCpuLoad > 80)
            {
                htCpuInfo["iswarn"] = true;
            }
            else
            {
                htCpuInfo["iswarn"] = false;
            }

            string strDescribe = string.Empty;
            //获取CPU个数
            int iCpuNum = Environment.ProcessorCount;
            strDescribe += "CPU个数:" + iCpuNum + ";";
            //获取单个CPU占用率
            for (int i = 0; i < iCpuNum; i++)
            {
                //pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", i.ToString());
                pcCpuLoad.CategoryName = "Processor";
                pcCpuLoad.CounterName = "% Processor Time";
                pcCpuLoad.InstanceName = i.ToString();
                fCpuLoad = pcCpuLoad.NextValue();
                strDescribe += "#" + i + "CPU使用率为:" + fCpuLoad + ";";
            }
            htCpuInfo["describe"] = strDescribe;

            PhoneBook.ServerMoniter.ServerMoniter.AddLog(htCpuInfo);
        }
        #endregion

        #region 获取硬盘信息
        /// <summary>
        /// 获取硬盘信息 WMI实现
        /// </summary>
        /// <returns></returns>
        private void GetStorageInfo()
        {
            Hashtable htStorageInfo = new Hashtable();

            SelectQuery sq = new SelectQuery("select * from win32_logicaldisk");

            ManagementObjectSearcher objSearch = new ManagementObjectSearcher(sq);

            foreach (ManagementObject disk in objSearch.Get())
            {
                string strPartitionName = disk["DeviceID"].ToString();

                string strDiskType = disk["DriveType"].ToString();

                //硬盘 0-未知设备 1-未分区 2-可移动磁盘 3-硬盘 4-网络驱动器 5-光驱 6-内存磁盘
                if (strDiskType == "3")
                { 
                    //获取磁盘空间
                    double dFreeSpace = Convert.ToDouble(disk["FreeSpace"]) / (1024 * 1024 * 1024);
                    double dSumSpace = Convert.ToDouble(disk["Size"]) / (1024 * 1024 * 1024);

                    //htStorageInfo.Add("Storage-" + strPartitionName, (dFreeSpace / dSumSpace * 100) + "%");
                    double dResult = Math.Round(dFreeSpace / dSumSpace * 100, 2);

                    htStorageInfo["monitertype"] = "Storage";
                    htStorageInfo["monitertypedetail"] = strPartitionName;
                    htStorageInfo["monitervalue"] = dResult;

                    if (dResult <= 20)
                    {
                        htStorageInfo["iswarn"] = true;
                    }
                    else
                    {
                        htStorageInfo["iswarn"] = false;
                    }

                    htStorageInfo["describe"] = string.Empty;

                    PhoneBook.ServerMoniter.ServerMoniter.AddLog(htStorageInfo);


                }
            }
        }
        #endregion

        #region 获取内存信息
        /// <summary>
        /// 获取内存信息
        /// </summary>
        /// <returns>Hashtable</returns>
        private void GetMemoryInfo()
        {
            Hashtable htMemoryInfo = new Hashtable();

            //总内存
            ManagementClass wmiMemory = new ManagementClass("Win32_PhysicalMemory");

            ManagementObjectCollection objCollection = wmiMemory.GetInstances();

            double dMemorySum = 0;

            foreach (ManagementObject obj in objCollection)
            {
                dMemorySum += (Math.Round(Int64.Parse(obj.Properties["Capacity"].Value.ToString()) / 1024 / 1024 / 1024.0, 1));
            }
            //可用内存
            wmiMemory = new ManagementClass("Win32_PerfFormattedData_PerfOS_Memory");
            objCollection = wmiMemory.GetInstances();
            double dFreeMemory = 0;
            foreach (ManagementObject obj in objCollection)
            {
                dFreeMemory += (Math.Round(Int64.Parse(obj.Properties["AvailableMBytes"].Value.ToString()) / 1024.0, 1));
            }

            double dResult = Math.Round(dFreeMemory / dMemorySum, 2) * 100;

            htMemoryInfo["monitertype"] = "Memory";
            htMemoryInfo["monitertypedetail"] = "";
            htMemoryInfo["monitervalue"] = dResult;
            if (dResult <= 20)
            {
                htMemoryInfo["iswarn"] = true;
            }
            else
            {
                htMemoryInfo["iswarn"] = false;
            }

            htMemoryInfo["describe"] = "总内存:" + Math.Round(dMemorySum, 2) + "G;空余内存:" + Math.Round(dFreeMemory, 2) + "G";

            PhoneBook.ServerMoniter.ServerMoniter.AddLog(htMemoryInfo);
        }
        #endregion

        #region 判断网络是否连接
        /// <summary>
        /// 判断网络是否连接
        /// </summary>
        /// <returns></returns>
        private void isNetworkConnected()
        {
            int iFlag;
            bool bResult = false;
            if (InternetGetConnectedState(out iFlag, 0))
            {
                bResult = true;
            }
            else
            {
                bResult = false;
            }

            Hashtable htNetInfo = new Hashtable();
            htNetInfo["monitertype"] = "NET";
            htNetInfo["monitertypedetail"] = "";
            htNetInfo["monitervalue"] = bResult;
            if (!bResult)
            {
                htNetInfo["monitervalue"] = "未连接";
                htNetInfo["iswarn"] = true;
            }
            else
            {
                htNetInfo["monitervalue"] = "已连接";
                htNetInfo["iswarn"] = false;
            }

            htNetInfo["describe"] = string.Empty;

            PhoneBook.ServerMoniter.ServerMoniter.AddLog(htNetInfo);
        }
        #endregion

        #region 获取指定进程是否存在
        /// <summary>
        /// 获取指定进程是否存在
        /// </summary>
        /// <returns></returns>
        private void GetProcessStatus()
        {
            Hashtable htProcessStatus = new Hashtable();

            //监控进程名称
            string[] strProcessNames = new string[] { 
                "inetinfo.exe",
                "sqlservr.exe",

            };

            foreach (string strProcessName in strProcessNames)
            {
                Process[] process = Process.GetProcessesByName(strProcessName);

                if (process == null || process.Count() > 0)
                {
                    htProcessStatus["monitertype"] = "Process";
                    htProcessStatus["monitertypedetail"] = strProcessName;
                    htProcessStatus["monitervalue"] = "未运行";
                    htProcessStatus["iswarn"] = true;
                    htProcessStatus["describe"] = string.Empty;
                    PhoneBook.ServerMoniter.ServerMoniter.AddLog(htProcessStatus);
                }
            }
        }
        #endregion

        #region 执行服务
        /// <summary>
        /// 执行服务
        /// </summary>
        public void RunThreadService()
        {
            Hashtable htResult = new Hashtable();

            while (bServiceRunning)
            {
                // 执行的操作
                try
                {
                    //CPU
                    GetCPUInfo();
                }
                catch (Exception e)
                {
                    //log.Error("SiteId:" + globalSiteId + ";SiteUrl:" + globalApiUrl + ";抓取团购信息时发生错误：", ex);
                }

                try
                {
                    //硬盘
                    GetStorageInfo();
                }
                catch
                { 
                    
                }

                try
                {
                    //内存
                    GetMemoryInfo();
                }
                catch
                { 
                    
                }

                try
                {
                    //网络连接
                    isNetworkConnected();
                }
                catch
                {

                }

                try
                {
                    //进程
                    GetProcessStatus();
                }
                catch
                {

                }
                // 程序休息
                if (bServiceRunning)
                {
                    Thread.Sleep(300 * 1000);
                }
            }
        }
        #endregion

        #region 退出服务
        /// <summary>
        /// 退出服务
        /// </summary>
        public void ExitThreadService()
        {
            this.bServiceRunning = false;
        }
        #endregion
    }
}
